const app = getApp()
import http from '../../utils/request.js';
import alert from '../../utils/alert.js';
import QR from '../../utils/qrcode.js';
import barcode from '../../utils/barcode.js';
var UiUtils = require("../../utils/ui.js");
const sliderWidth = 96

Page({
  data: {
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    canReceiveCoupons: [],
    expireCoupons: [],
    canUseCoupons: [],
    barNumber: '123456',
    barVisible: false
  },
  /**
 * 生命周期函数--监听页面加载
 */
  onLoad: function (options) {
    this.getSystemInfo()
    this.getCouponLists()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  getSystemInfo: function () {
    const that = this
    wx.getSystemInfo({
      success(res) {
        that.setData({
          sliderLeft: (res.windowWidth / 3 - sliderWidth) / 2,
        })
      }
    })
  },

  getCouponLists: function () {
    http.post(app.config.service.getCouponLists, { app_id: app.globalData.app_id }).then(data => {
      this.setData({
        canReceiveCoupons: data.canReceiveCoupons,
        canUseCoupons: data.canUseCoupons,
        expireCoupons: data.expireCoupons
      })
    }, err => {
      alert.alert(err)
    });
  },

  tabClick: function (e) {
    this.setData({
      activeIndex: parseInt(e.currentTarget.dataset.id),
    })
  },

  swiperChange: function (e) {
    this.setData({
      activeIndex: parseInt(e.detail.current)
    })
  },

  useCoupon: function (e) {
    var w = UiUtils.rpx2px(680)
    var h = UiUtils.rpx2px(200)
    barcode.createBarcode('barcodeCanvas', e.currentTarget.dataset.coupon.coupon_id, w, h);
    var w2 = UiUtils.rpx2px(550)
    QR.qrApi.draw(e.currentTarget.dataset.coupon.coupon_id, "qrcodeCanvas", w2, w2);
    var code = barcode.formatBarCode(e.currentTarget.dataset.coupon.coupon_id, " ")

    this.setData({
      barVisible: true,
      barNumber: e.currentTarget.dataset.coupon.coupon_id,
      barcode: code
    })
  },

  receiveCoupon: function (e) {
    var coupontype = e.currentTarget.dataset.coupontype;
    http.post(app.config.service.receiveCoupon, { app_id: app.globalData.app_id, type_id: coupontype.type_id }).then(data => {
      console.log(data)
      alert.toast("领取成功");
    }, err => {
      console.log(err);
      alert.alert(err)
    });
  },

  onBarVisibleClose: function (e) {
    this.setData({
      barVisible: false,
    })
  }

})